<?php
/**
 * 权限模型
 *
 * @author haifeng.wu
 */
class Application_Model_Acl 
{
	private $acl;
	private $userLoginModel;
	private $cache;
	private $getLoginRow;

	public function __construct() 
	{
		$this->acl = new Zend_Acl();
		$this->cache = new Application_Model_Cache(28800);
		$this->userLoginModel = Application_Model_UserLogin::getInstance();
		$this->getLoginRow = $this->userLoginModel->getLoginedRow();
	}

	/**
     * 设置用户权限到acl并且缓存到cache
     * 
     * @return volid
     */
	public function setAcl()
	{
		$getUserCurrentAllRole = $this->userLoginModel->getUserCurrentAllRole();
		foreach ($getUserCurrentAllRole as $k=>$v) {
			$this->acl->addrole(new Zend_Acl_Role($v['roleId']));
		}
		$getAllRoleResource = $this->userLoginModel->getAllRoleResource();
		$aclRoleResource = array();
		foreach ($getAllRoleResource as $key => $value) {
			$this->acl->add(new Zend_Acl_Resource($value['module'].$value['controller'].$value['action']));
			$aclRoleResource[$value['roleId']][] = $value['module'].$value['controller'].$value['action'];
		}
		foreach ($aclRoleResource as $k=>$v) {
			$this->acl->allow($k, $v);
		}
		$strAcl = serialize($this->acl);
		$this->cache->write($this->getLoginRow['userId'], $strAcl);
	}
	
	/**
     * 角色判断权限是否可用
     * 
     * @return boolean 
     */
	public function menuIsAllow($role = array(), $resource)
	{
		if (!$this->cache->get($this->getLoginRow['userId'])) {
			$this->setAcl();
		}
		$getAcl = unserialize($this->cache->get($this->getLoginRow['userId']));
		if(!$getAcl->has($resource)) {
			return false;
		}
		$isAllow = 0;
		foreach ($role as $item) {
			if (!$getAcl->hasRole($item)) {
				continue;
			}
			if ($getAcl->isAllowed($item, $resource)) {
				$isAllow = 1;
				break;
			}
		}
		return $isAllow;
	}


}